package com.bwie.controller;

import com.bwie.utils.R;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @Author: Mikey
 * @Date: 2025/9/9 13:10
 * @Description:
 **/
@RestController
@RequestMapping("shop/index")
@CrossOrigin
public class FileUploadController {

    @Value("${minio.endpoint}")
    private String endpoint;

    @Value("${minio.accessKey}")
    private String accessKey;

    @Value("${minio.secretKey}")
    private String secretKey;

    @Value("${minio.bucketName}")
    private String bucketName;


    /***
     * @author: 秋晚
     * @description:图片上传
     * @params: [org.springframework.web.multipart.MultipartFile]
     * @return: com.bwie.utils.R
     * @date: 2025/9/9 13:13
     */
    @PostMapping("upload")
    public R uploadFile(MultipartFile file) throws Exception{
        //实例化Minio对象
        MinioClient minioClient = MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();


        //判断桶是否存在 不存在就创建
        boolean b = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if(b){
            System.out.println("桶已存在!");
        }else{
            //创建
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }

        //随机生成图片名称
        String fileName=System.currentTimeMillis()+ UUID.randomUUID().toString();

        //上传
        minioClient.putObject(PutObjectArgs.builder()
                .object(fileName)
                .bucket(bucketName)
                .contentType(file.getContentType())
                .stream(file.getInputStream(),file.getSize(),-1)
                .build());


        //拼接返回路径
        String path=endpoint+"/"+bucketName+"/"+fileName;

        return R.OK(path);
    }

}
